/*
 * Copy Right: Tencent ISUX
 * Project: QAM（Qzone模块化页面搭建平台）
 * Description: 项目管理
 * Author: kundy
 * date: 2011-11-17
 */

var global_id=functions.getRequest("id")*1;
var global_action=functions.getRequest("action");

 parent.nav_set(1);
 
var project = {
	addInit:function(){
		if(global_action=="edit"){
			$("#btn_save").click(function(){project.update();});
			$('#page_title').html("<i class=\"ico ico_manage\"></i><span>修改项目</span>");
			project.edit();
		}
		else{
			$("#btn_save").click(function(){project.add();});
			$('#page_title').html("<i class=\"ico ico_project_add\"></i><span>添加项目</span>");
		}
		
		
		//不允许输入空格
		//鼠标离开、复制等！
		$("#name").mouseout(function () {
			this.value=this.value.replace(/\s/g,'');
		});
		$("#name").focusout(function () {
			this.value=this.value.replace(/\s/g,'');
			check_project_name(this.value);
		});
		$(".like_select").click(
			function(){$(this).parent().find('.select_drop_down').css({visibility: "visible",display: "none"}).show();}
		);
		$(".type_select").hover(
			function(){},
			function(){$(this).find('.select_drop_down').delay(1000).hide();}
		);
		
		$("#upload_file_area")[0].ondragenter =function(){event.stopPropagation(); event.preventDefault();};
		$("#upload_file_area")[0].ondragover =function(){event.stopPropagation(); event.preventDefault();};
		$("#upload_file_area")[0].ondrop =function(){event.stopPropagation(); event.preventDefault();dodrop(event)};
		
	},
	/*------------ 检查用户输入的项目名称 ------------*/
    checkProjectName : function(project_name){
		var data_area=[];
		if(global_action=="edit"){
			data_area.push([ "id" , global_id ]);
		}
		data_area.push([ "name" , project_name ]);
		var data_str=functions.requestToString(data_area);

        $.ajax({
                url: cgipath+'project-checkName',type: 'POST', data: data_str, dataType: 'json',timeout: ajax_timeout, error: function(){notify.show(2,"请求数据失败，请刷新页面");},
				success:this.handelCheckProjectName
        });
    },

    handelCheckProjectName : function(feedback){
		//ret=0：已存在项目名称
        if(feedback.ret=="0"){
			$("#fhint_area_name").show();
			$("#fhint_area_name").removeClass('fhint_succeed').addClass('fhint_error');
			$("#fhint_ico").removeClass('ico_succeed').addClass('ico_error');
			$("#fhint_text").text("亲，项目名称已存在了，换一个吧");
			
        }
        else if(feedback.ret=="3"){
           $("#fhint_area_name").show();
		   $("#fhint_area_name").removeClass('fhint_error').addClass('fhint_succeed');
		   $("#fhint_ico").removeClass('ico_error').addClass('ico_succeed');
		   $("#fhint_text").text("亲，这个名字起不错！");
        }
    },

    /*------------ 获取所有根项目信息 ------------*/
    showlist : function(){
		var data_area=[];
		data_area.push([ "root_flag" , 1 ]);
		data_area.push([ "search_flag" , 0 ]);
		data_area.push([ "order" , "id" ]);
		data_area.push([ "desc" , 0 ]);
		var data_str=functions.requestToString(data_area);
		
        $.ajax({
                url: cgipath+'project-showlist', type: 'POST',data: data_str,dataType: 'json', timeout: ajax_timeout,error: function(){notify.show(2,"请求数据失败，请刷新页面");},
                success:this.handleShowlist
        });
    },

     handleShowlist : function(feedback){
        if(feedback.ret=="0"){
            //显示项目列表
            var project_list_array=feedback.listdata;
            for(var i=0;i<project_list_array.length;i++){
				if(project_list_array[i].id!=1){
					var tr="<tr>";
					tr+="<td><a title=\""+project_list_array[i].info+"\" href='project_manage_sub.htm?"+project_list_array[i].id+"'>"+project_list_array[i].name+"</a>";
					if(project_list_array[i].svn_flag!=1)tr+="<i class=\"ico ico_msg\" title=\"错误的svn\"></i>";
					tr+="</td>"; 
					tr+="<td>"+project_list_array[i].author+"</td>"; 
					tr+="<td class='col_proj_svn'><span title=\""+project_list_array[i].svn+"\">"+project_list_array[i].svn+"</span></td>";
					var css_str="";
					for(var j=0;j<project_list_array[i].css_list.length;j++){
						
						css_str+="<div class=\"css_list_area\"><a href=\""+(cgipath+project_list_array[i].css_list[j].href)+"\" target=\"_blank\">"+project_list_array[i].css_list[j].name+"</a></div>";
					}
					tr+="<td>"+css_str+"</td>"; 
					tr+="<td class=\"add_tr_op\"><a href='project_manage_sub.htm?"+project_list_array[i].id+"'><i class='ico ico_settings'></i>管理子项目</a>";
					tr+="<a href='project.htm?action=edit&id="+project_list_array[i].id+"' class=\"op_sub_href\" ><i class='ico ico_edit'></i>编辑</a>";
					tr+="<a href='javascript:void(0);' class=\"op_sub_href\" onclick=\"project.delConfirm("+project_list_array[i].id+");\" ><i class=\"ico ico_del\"></i>删除</a></td>";
					tr+="</tr>";
					$("#project_list").append(tr);
				}
            }
        }
        else{
             message.show("message_div","",feedback.msg,4);
        }
    },
	
	/*------------ 获取所有父项目信息ID列表 ------------*/
    parentList : function(){
		var data_area=[];
		data_area.push([ "root_flag" , 1 ]);
		data_area.push([ "search_flag" , 0 ]);
		var data_str=functions.requestToString(data_area);
        $.ajax({
                url: cgipath+'project-showlist',type: 'POST',data: data_str,dataType: 'json',timeout: ajax_timeout,error: function(){notify.show(2,"请求数据失败，请刷新页面");},
                success:this.handleParentList
        });
    },

     handleParentList : function(feedback){
        if(feedback.ret=="0"){
            //显示项目列表
            var project_list_array=feedback.listdata;
			var ul="<ul>";
            for(var i=0;i<project_list_array.length;i++){
				if(project_list_array[i].id>1)ul+="<li><a onclick=\"project.chooseParentId(this)\" id=\""+project_list_array[i].id+"\" name=\""+project_list_array[i].name+"\" href=\"javascript:void(0);\">"+project_list_array[i].name+"</a></li>";
            }
			ul+="</ul>";
			 $("#parent_id_list").append(ul);
        }
        else{
            message.show("message_div","",feedback.msg,4);
        }
    },
	chooseParentId : function(obj){
         $('#parent_id_list').css('display', 'none');
		 $('#parent_id_name').html($(obj).attr("name"));
		 $('#parent_id').val($(obj).attr("id"));
    },
	/*------------ 获取所有项目类型信息ID列表 ------------*/
    typeList : function(){
        $.ajax({
                url: cgipath+'project-typeShowlist',type: 'POST',data: '',dataType: 'json',timeout: ajax_timeout,error: function(){notify.show(2,"请求数据失败，请刷新页面");},
                success:this.handleTypeList
        });
    },

     handleTypeList : function(feedback){
        if(feedback.ret=="0"){
            //显示项目列表
            var projectType_list_array=feedback.listdata;
			var ul="<ul>";
            for(var i=0;i<projectType_list_array.length;i++){
				ul+="<li><a onclick=\"project.chooseProjectType(this)\" id=\""+projectType_list_array[i].id+"\" name=\""+projectType_list_array[i].name+"\" href=\"javascript:void(0);\">"+projectType_list_array[i].name+"</a></li>";
            }
			ul+="</ul>";
			 $("#type_id_list").append(ul);
        }
        else{
            message.show("message_div","",feedback.msg,4);
        }
    },
	
	chooseProjectType : function(obj){
         $('#type_id_list').css('display', 'none');
		 $('#type_id_name').html($(obj).attr("name"));
		 $('#type_id').val($(obj).attr("id"));
    },
	

    /*------------ 添加一个项目 ------------*/
    add : function(){
        //收集项目信息
		 notify.show(1,"正在保存，请稍候...");
		var root_flag=$('[name=root_flag]:checked').val();
		var svn=$('#svn').val();
		if(root_flag==0)svn=$('#name').val();
		
		var data_area=[];
		data_area.push([ "name" , $('#name').val() ]);
		data_area.push([ "info" , $('#info').val() ]);
		data_area.push([ "svn" , svn ]);
		data_area.push([ "root_flag" , $('[name=root_flag]:checked').val() ]);
		data_area.push([ "typeid" , $("#type_id").val() ]);
		data_area.push([ "parentid" , $("#parent_id").val() ]);
		data_area.push([ "css_file_data" ,  $('#css_file_data').val() ]);
		var data_str=functions.requestToString(data_area);

        $.ajax({
            url:cgipath + 'project-add',type:'POST',data:data_str,dataType:'json',timeout: ajax_timeout,error:function () {notify.show(2,"请求数据失败，请刷新页面");},
            success:this.handleAdd
        });
    },

    handleAdd : function (feedback){
        if(feedback.ret=="0"){
           
			if($("[name='root_flag']:checked").val()==1)
				message.show("message_div","","添加成功",1,"","window.location.href='project_manage.htm';");
			else
				message.show("message_div","","添加成功",1,"","window.location.href='project_manage_sub.htm?"+$("#parent_id").val()+"'");
        }
        else{
            message.show("message_div","",feedback.msg,4);
        }
    },
	
	/*------------ 保存一个项目 ------------*/
    update : function(){
		notify.show(1,"正在保存，请稍候...");
		var root_flag=$('[name=root_flag]:checked').val();
		var svn=$('#svn').val();
		if(root_flag==0)svn=$('#name').val();
        //收集项目信息
		var data_area=[];
		data_area.push([ "id" , global_id ]);
		data_area.push([ "info" , $('#info').val() ]);
		data_area.push([ "name" ,  $('#name').val() ]);
		data_area.push([ "svn" ,  svn ]);
		data_area.push([ "root_flag" ,  $('[name=root_flag]:checked').val() ]);
		data_area.push([ "typeid" ,  $('#type_id').val() ]);
		data_area.push([ "parentid" ,  $('#parent_id').val() ]);
		data_area.push([ "css_file_data" ,  $('#css_file_data').val() ]);
		
		
		var data_str=functions.requestToString(data_area);

        $.ajax({
            url:cgipath + 'project-update',type:'POST',data:data_str,dataType:'json',timeout: ajax_timeout,error:function () {notify.show(2,"请求数据失败，请刷新页面");},
            success:function(feedback){
				if(feedback.ret=="0"){
					if($("[name='root_flag']:checked").val()==1)
						message.show("message_div","","保存成功",1,"","window.location.href='project_manage.htm';");
					else
						message.show("message_div","","保存成功",1,"","window.location.href='project_manage_sub.htm?"+$("#parent_id").val()+"'");
				}
				else{
					message.show("message_div","",feedback.msg,4);
				}
			}
        });
    },

	/*------------ 获取并显示一条项目信息 ------------*/
    show : function(id,obj){
		var data_str="&id="+id;
        $.ajax({
            url:cgipath + 'project-getinfo',type:'POST',data:data_str,dataType:'json',timeout: ajax_timeout,error:function () {notify.show(2,"请求数据失败，请刷新页面");},
            success:function(feedback){
				if(feedback.ret=="0"){
					var td="";
					td+="<td><a href='project_manage_sub.htm?"+feedback.record.id+"'>"+feedback.record.name+"</a></td>";         //项目名称
					td+="<td>"+feedback.record.author+"</td>";         //项目管理员
					td+="<td class='col_proj_svn'>"+feedback.record.svn+"</td>";         //SVN路径
					td+="<td class=\"add_tr_op\"><a href='project_manage_sub.htm?"+feedback.record.id+"'><i class='ico ico_settings'></i>管理子项目</a>";
					td+="<a href='javascript:void(0);' class=\"op_sub_href\" onclick=\"project.edit("+feedback.record.id+",this.parentNode.parentNode);\" ><i class='ico ico_edit'></i>编辑</a>";
					td+="<a href='javascript:void(0);' class=\"op_sub_href\" onclick=\"project.delConfirm("+feedback.record.id+");\" ><i class=\"ico ico_del\"></i>删除</a></td>";
					$(obj).html(td);
				}
				else{
					message.show("message_div","",feedback.msg,4);
				}
			
			}
        });
    },
	
	
    edit : function(id){
		var data_str="&id="+global_id;
        $.ajax({
            url:cgipath + 'project-getinfo',type:'POST',data:data_str,dataType:'json',timeout: ajax_timeout,error:function () {notify.show(2,"请求数据失败，请刷新页面");},
            success:function(feedback){
				if(feedback.ret=="0"){
					$("#name").val(feedback.record.name);
					$("#info").val(feedback.record.info);
					$("#svn").val(feedback.record.svn);
					$("[name=root_flag][value='"+feedback.record.root_flag+"']").attr("checked","");
					if($("[name='root_flag']:checked").val()==1){
						$('#more_info').hide();
						$('#more_svn').show();
					}
					else{
						$('#more_svn').hide();
						$('#more_info').show();
					}
					$("#parent_id").val(feedback.record.parentid);
					$("#parent_id_name").html(feedback.record.parent_name);
					$("#type_id").val(feedback.record.typeid);
					$("#type_id_name").html(feedback.record.type_name);
					var innerhtml="";
					var css_file_data="[";
					for(var i=0;i<feedback.record.css_list.length;i++){
						innerhtml+="<li><span>"+feedback.record.css_list[i].name+"</span><a href=\"javascript:void(0);\" onclick=\"del_css(this,'"+feedback.record.css_list[i].name+"')\" ><i class=\"ico ico_x\"></i></a></li>";
						if(i>0)css_file_data+=",";
						css_file_data+="{\"name\":\""+feedback.record.css_list[i].name+"\",\"data\":\"\"}";
					}
					css_file_data+="]";
					$("#css_file_list").html(innerhtml);
					$("#css_file_data").val(css_file_data);

				}
				else{
					message.show("message_div","",feedback.msg,4);
				}
			
			}
        });
    },

	
	 /*------------ 删除项目 ------------*/
	 
	delConfirm:function(id){
		message.show("message_div","","确实要删除吗？",2,"","project.del("+id+");");
	},
	
    del : function(id){
		var data_str="&id="+id;
        $.ajax({
            url:cgipath + 'project-del',type:'POST',data:data_str,dataType:'json',timeout: ajax_timeout,error:function () {notify.show(2,"请求数据失败，请刷新页面");},
            success:this.handledel
        });
    },

    handledel : function (feedback){
        if(feedback.ret=="0"){
            message.show("message_div","","删除成功",1,"","window.location.reload();");
        }
        else{
            message.show("message_div","",feedback.msg,4);
        }
    }

}



function check_project_name(project_name){
	if(project_name==""){
		$("#fhint_area_name").show();
		$("#fhint_area_name").removeClass('fhint_succeed').addClass('fhint_error');
		$("#fhint_ico").removeClass('ico_succeed').addClass('ico_error');
		$("#fhint_text").text("亲，项目名称要填的");
	}
	else if(!(functions.checkAlnum(project_name))  && $('[name=root_flag]:checked').val()==0){
		$("#fhint_area_name").show();
		$("#fhint_area_name").removeClass('fhint_succeed').addClass('fhint_error');
		$("#fhint_ico").removeClass('ico_succeed').addClass('ico_error');
		$("#fhint_text").text("亲，非根项目的名称由字母、下划线或数字组成！它将与父项目的SVN构成完整的SVN路径！");
	}
	else
		project.checkProjectName(project_name);
}


function dodrop(event)
{
	var dt = event.dataTransfer;
	var files = dt.files;
	var innterhtml="";
	var file_data="";
	for (var i = 0,f; f=files[i],i < files.length; i++) {
		if(f.type=="text/css"){
			var data_flag=true;
			
			var imageReader = new FileReader();
			imageReader.onload = (function(aFile) {
			  return function(e) {
					file_data=e.target.result;
					var css_data=JSON.parse($("#css_file_data").val());
					for(var j=0;j<css_data.length;j++){
						if(css_data[j].name==aFile.fileName){
							css_data[j].data=file_data;
							data_flag=false;
						}
					}
					if(data_flag){
						//新增
						css_data.push({"name":aFile.fileName,"data":file_data});
						$("#css_file_list").append("<li><span>"+aFile.fileName+"</span><a href=\"javascript:void(0);\" style=\"color:#C6DEDE\" onclick=\"del_css(this,'"+aFile.fileName+"')\" ><i class=\"ico ico_x\"></i></a></li>");
					}
					else{
						//替换
						$("#css_file_list").find("span").each(function(){
							if($(this).text()==aFile.fileName)
								$(this).css("font-weight","bold");
								$(this).css("color","#C6DEDE");
						})
					}
					$("#css_file_data").val(JSON.stringify(css_data));
			  };
			})(f);
			imageReader.readAsDataURL(f);
		}
	}
	
}

function del_css(obj,name){
	$(obj).parent().remove();;
	var css_data=JSON.parse($("#css_file_data").val());
	var css_data_new=[];
	for(var i=0;i<css_data.length;i++){
		if(css_data[i].name!=name){
			css_data_new.push(css_data[i]);
		}
	}
	$("#css_file_data").val(JSON.stringify(css_data_new));
}
